package lxmysqlv2

import (
	"fmt"
	"gitee.com/lxgow/lxconv"
	"gitee.com/lxgow/lxerror"
	"gitee.com/lxgow/lxmysql"
	lxredisv2 "gitee.com/lxgow/lxredis/v2"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

// query
// 创建时间:2024/5/21 11:12
// 创建人:lixu

type QueryCacheConfig struct {
	DB        string //数据库缓存 Redis数据库索引
	Name      string //缓存的名字
	IndexName string //REDIS 数据库索引
	Exexpire  int    //缓存过期时间 -1不使用缓存
}

type QueryConfig struct {
	SQL   string //sql
	UseDB string //指定数据库
	Cache QueryCacheConfig
	Orm   orm.Ormer //实例化 ORM
}

const PREFIX = "lxmysqlv2::"

// formatCacheName 缓存的名字
func formatQueryCache(cfg QueryConfig) (errs []error) {
	if cfg.Cache.Name == "" {
		cfg.Cache.Name = lxconv.EncryMD5(cfg.SQL + cfg.UseDB)
	}

	if cfg.Cache.DB == "" {
		cfg.Cache.DB = lxmysql.LXMYSQLCACHEDB
	}

	if cfg.Cache.DB == "" {
		cfg.Cache.DB = "0"
	}

	//if cfg.Orm == nil {
	//	cfg.Orm = orm.NewOrm()
	//}

	if cfg.Cache.Exexpire == 0 {
		cfg.Cache.Exexpire = lxmysql.DEFAULT_EXPIRE
	}

	return
}

func dbRead(result interface{}, config QueryConfig) (err error) {
	if config.Orm == nil {
		config.Orm = orm.NewOrm()
	}

	if config.UseDB != "" {
		err = config.Orm.Using(config.UseDB)
		if err != nil {
			logs.Error("Using error", err)
			return
		}
	}

	// 直接送数据库 获取
	_, err = config.Orm.Raw(config.SQL).QueryRows(result)

	if err != nil {
		logs.Error("Raw error", err)
		return
	}

	_, err = lxerror.DBError(err)

	if err != nil {
		err = fmt.Errorf("Raw error::%s", err.Error(), lxconv.JsonEncode(config))
		logs.Error("dbRead end error", err)
		return
	}

	return
}

// Query 查询列表
func Query(result interface{}, config QueryConfig) (err error) {

	if config.Cache.Exexpire < 0 {
		return dbRead(result, config)
	}

	_ = formatQueryCache(config)

	var (
		content string
	)

	_rds := lxredisv2.Cpms{
		IndexName: config.Cache.IndexName,
		Name:      config.Cache.Name,
		Db:        config.Cache.DB,
		Prefix:    PREFIX,
	}

	content, _ = _rds.Get(&result)
	if content != "" {
		// 查到数据直接返回
		return
	}

	err = dbRead(result, config)
	if err != nil {
		err = fmt.Errorf("dbRead error::%s", err.Error())
		logs.Error("dbRead end error", err)
		return
	}

	_rds.Val = result

	if config.Cache.Exexpire < 1 {
		config.Cache.Exexpire = 600
	}

	_rds.Set(config.Cache.Exexpire)

	return
}

func DeleteCache(qc QueryCacheConfig) (err error) {

	_rds := lxredisv2.Cpms{
		IndexName: qc.IndexName,
		Name:      qc.Name,
		Prefix:    PREFIX,
		Db:        qc.DB,
	}

	err = _rds.KeyDel()

	return
}
